<template>
  <div class="workflow-container">
    <el-row
      class="tool-bar"
      align="middle"
    >
      <el-col
        :span="10"
        :offset="2"
      >
        <el-icon class="el-alert__icon text-warning">
          <ele-WarningFilled />
        </el-icon>
        <span class="text-warning">{{ $t("workflow.flowDesign.savingProcessNote") }}</span>
      </el-col>
      <el-col :span="4">
        <el-dropdown class="flex">
          <span class="el-dropdown-link">
            {{ $t("workflow.flowDesign.processVersion") }}
            <span class="text-warning">V{{ selectedDesignProcess.version }}</span>
            <el-tag
              :type="selectedDesignProcess.status == '2' ? 'success' : 'warning'"
              size="default"
              class="ml15"
            >
              {{ selectedDesignProcess.status == "2" ? $t("workflow.flowDesign.enabled") : $t("workflow.flowDesign.design") }}
            </el-tag>
            <el-icon class="el-icon--right">
              <ele-ArrowDown />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="d in designList"
                :key="d.id"
                :command="d.id"
                class="m4"
                @click="handleDesignVersionChange(d)"
              >
                {{ $t("workflow.flowDesign.processVersion") }}
                <span class="text-warning mr5">V{{ d.version }}</span>
                <el-tag
                  :type="d.status == '2' ? 'success' : 'warning'"
                  size="default"
                  class="ml15"
                >
                  {{ d.status == "2" ? $t("workflow.flowDesign.enabled") : $t("workflow.flowDesign.design") }}
                </el-tag>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
      <el-col :span="7">
        <el-button
          size="default"
          v-re-click
          @click="saveBusinessDesign"
        >
          {{ $t("workflow.flowDesign.save") }}
        </el-button>
        <el-button
          size="default"
          v-re-click
          type="success"
          @click="downloadBpmnFile"
        >
          {{ $t("workflow.flowDesign.downloadBpmn") }}
        </el-button>
        <el-button
          size="default"
          type="danger"
          v-re-click
          @click="publishProcess"
        >
          {{ $t("workflow.flowDesign.enable") }}
        </el-button>
      </el-col>
    </el-row>
    <el-scrollbar :height="`${wdHeight - 100}px`">
      <div class="fd-nav-content">
        <section class="dingflow-design">
          <div class="zoom">
            <div
              :class="'zoom-out' + (nowVal == 50 ? ' disabled' : '')"
              @click="zoomSize(1)"
            />
            <span>{{ nowVal }}%</span>
            <div
              :class="'zoom-in' + (nowVal == 300 ? ' disabled' : '')"
              @click="zoomSize(2)"
            />
          </div>
          <div
            id="box-scale"
            :style="'transform: scale(' + nowVal / 100 + '); transform-origin: 50% 0px 0px;'"
            class="box-scale"
          >
            <nodeWrap
              v-model:is-tried="isTried"
              v-model:process-node="processConfig.processNode"
            />
            <div class="end-node">
              <div class="end-node-circle" />
              <div class="end-node-text">{{ $t("workflow.flowDesign.endOfProcess") }}</div>
            </div>
          </div>
        </section>
      </div>
    </el-scrollbar>
    <div class="workflow-drawer">
      <approverDrawer :form-key="formKey" />
      <copyerDrawer :form-key="formKey" />
      <conditionDrawer :form-key="formKey" />
      <promoterDrawer :form-key="formKey" />
    </div>
    <approval-notify-config />
  </div>
</template>

<script setup lang="ts" name="FormWorkFLow">
import { onActivated, ref } from "vue";
import { useRoute } from "vue-router";
import { i18n } from "@/i18n";
import { useWindowSize } from "@vueuse/core";
import {
  convertBpmnRequest,
  getBusinessDesignListRequest,
  publishBusinessDesignRequest,
  saveBusinessDesignRequest
} from "@/api/workflow/workflow";
import { getProjectRequest } from "@/api/project/form";
import { jsonSimpleClone, removeHtmlTag } from "@/views/formgen/utils";
import { defaultProcessData } from "./defaultProcess";

import nodeWrap from "./nodeWrap.vue";
import approverDrawer from "./drawer/approverDrawer.vue";
import conditionDrawer from "./drawer/conditionDrawer.vue";
import copyerDrawer from "./drawer/copyerDrawer.vue";
import promoterDrawer from "./drawer/promoterDrawer.vue";
import { MessageUtil } from "@/utils/messageUtil";
import { useFormWorkflow } from "@/stores/formWorkflow";
import ApprovalNotifyConfig from "@/views/form/workflow/components/ApprovalNotifyConfig.vue";

// 响应式变量
const designList = ref<any[]>([]);
// 当前选择的流程设计
const selectedDesignProcess = ref<Record<string, any>>({
  version: 1,
  status: "1",
  scheme: {}
});
const isTried = ref(false);
const nowVal = ref(100);
// 流程配置 后端保存配置
const processConfig = ref<any>({
  // 流程基础信息
  process: {},
  // 流程节点
  processNode: {}
});
const formKey = ref<string>("");

// 获取窗口大小
const { height: wdHeight } = useWindowSize();

// 路由信息
const route = useRoute();

/** 调整缩放 */
const zoomSize = (type: number) => {
  if (type === 1 && nowVal.value > 50) {
    nowVal.value -= 10;
  } else if (type === 2 && nowVal.value < 300) {
    nowVal.value += 10;
  }
};

const formWorkFlowStore = useFormWorkflow();

const getProcessConfigData = () => {
  return {
    ...jsonSimpleClone(selectedDesignProcess.value),
    name: processConfig.value.process.name,
    scheme: {
      ...processConfig.value,
      startUserConfig: formWorkFlowStore.promoterConfig
    },
    formKey: formKey.value
  };
};

/** 获取流程设计列表 */
const getBusinessDesignList = async () => {
  const res = await getBusinessDesignListRequest(formKey.value);
  designList.value = res.data || [];
  // 初始化默认流程
  if (!designList.value || !designList.value.length) {
    // 默认的流程配置
    let processData = JSON.parse(JSON.stringify(defaultProcessData));
    processData.process.processId = "process" + formKey.value;
    processConfig.value = processData;
    await formWorkFlowStore.updatePromoterConfig(processConfig.value?.startUserConfig);
  } else {
    await setProcessData(designList.value[0]);
  }
};

const handleDesignVersionChange = (data: any) => {
  if (data) {
    setProcessData(data);
  }
};

const setProcessData = async (data: any) => {
  // 默认的流程配置
  let processData = JSON.parse(JSON.stringify(defaultProcessData));
  selectedDesignProcess.value = data;
  if (data.scheme) {
    processData = { ...processData, ...data.scheme };
  }
  console.log(processData);
  processConfig.value = processData;
  await formWorkFlowStore.updatePromoterConfig(processConfig.value?.startUserConfig);
};

/** 保存流程设计 */
const saveBusinessDesign = async () => {
  const res = await saveBusinessDesignRequest(getProcessConfigData());
  if (res.data) {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
    await getBusinessDesignList();
  }
};

/** 发布流程 */
const publishProcess = async () => {
  const res = await publishBusinessDesignRequest(getProcessConfigData());
  if (res.data) {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
    await getBusinessDesignList();
  }
};

/** 下载 BPMN 文件 */
const downloadBpmnFile = async () => {
  const workflow = jsonSimpleClone(processConfig.value);
  const res = await convertBpmnRequest(JSON.stringify(workflow));
  const content = res.data;
  const blob = new Blob([content]);
  const elink = document.createElement("a");
  elink.download = `${removeHtmlTag(workflow.process.name)}.bpmn`;
  elink.style.display = "none";
  elink.href = URL.createObjectURL(blob);
  document.body.appendChild(elink);
  elink.click();
  URL.revokeObjectURL(elink.href);
  document.body.removeChild(elink);
};

// 生命周期
onActivated(async () => {
  formKey.value = route.query.key as string;
  await formWorkFlowStore.loadFormAllFields(formKey.value);
  await getBusinessDesignList();
  getProjectRequest(formKey.value).then(res => {
    processConfig.value.process.name = res.data.name;
  });
});
</script>

<style lang="scss">
@use "./workflow.css" as *;

.error-modal-list {
  width: 455px;
}

.workflow-container {
  background: url("")
    repeat;
}

.tool-bar {
  background-color: rgba(250, 250, 250, 0.8);
  border-bottom: 1px dashed #e8e8e8;
}
</style>
